package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.LinkMapper;
import com.itheima.pojo.Link;
import com.itheima.service.LinkService;
import com.itheima.utils.UuidUtil;
import com.itheima.vo.LinkVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class LinkServiceImpl implements LinkService {

    @Autowired
    private LinkMapper linkMapper;

    /**
     * 添加友链
     * @param linkVo
     */
    @Override
    public void add(LinkVo linkVo) {
        Link link = new Link();
        BeanUtils.copyProperties(linkVo,link);
        link.setCreateTime(new Date());
        link.setUid(UuidUtil.getUuid());
        link.setUpdateTime(new Date());
        link.setStatus((byte) 0);
        linkMapper.insertSelective(link);
    }

    /**
     * 查询友链
     * @param linkVo
     * @return
     */
    @Override
    public PageInfo list(LinkVo linkVo) {
        if (linkVo==null){
            return new PageInfo(linkMapper.selectAll());
        }
        if (linkVo.getCurrentPage()!=null&&linkVo.getPageSize()!=null){
            PageHelper.startPage(linkVo.getCurrentPage(),linkVo.getPageSize());
        }
        Example example = new Example(Link.class);
        Example.Criteria criteria = example.createCriteria();
        if (linkVo.getKeyword()!=null){
            criteria.orLike("title","%"+linkVo.getKeyword()+"%");
        }
        List<Link> links = linkMapper.selectByExample(example);
        return new PageInfo(links);
    }

    /**
     * 删除友链
     * @param linkVo
     */
    @Override
    @Transactional
    public void delete(LinkVo linkVo) {
        Link link = new Link();
        BeanUtils.copyProperties(linkVo,link);
        int i=linkMapper.deleteByPrimaryKey(link);
        if (i<=0){
            throw new RuntimeException("没有这个链接");
        }
    }

    /**
     * 修改友链
     * @param linkVo
     */
    @Override
    public void edit(LinkVo linkVo) {
        Link link = new Link();
        BeanUtils.copyProperties(linkVo,link);
        link.setUpdateTime(new Date());
        int i = linkMapper.updateByPrimaryKeySelective(link);
        if (i<=0){
        throw new RuntimeException("没有这个链接");
        }
    }

    /**
     * 置顶友链
     * @param linkVo
     */
    @Override
    public void stick(LinkVo linkVo) {
        //查询当前表中最大的sort值
        Integer maxSort = linkMapper.findMaxSort();
        Link link = new Link();
        BeanUtils.copyProperties(linkVo,link);
        //加一赋值给link
        link.setSort(maxSort+1);
        linkMapper.updateByPrimaryKeySelective(link);
    }


}


